"""
To provide some utils such as *tags* for the other handlers.

2019-3-25 by Stone at GDOU-KC
"""
import time

import settings as st
import tools


# ===== ===== ===== =====
# Exceptions
# ===== ===== ===== =====
__metaclass__ = type


class ExpireException(Exception):
    def __init__(self, *args, **kw):
        super().__init__(*args, **kw)


# ===== ===== ===== =====
# Constants
# ===== ===== ===== =====
EXPIRED = 'expired'  # a flag


# ===== ===== ===== =====
# Global variables
# ===== ===== ===== =====
class Tags:
    """Basically, a tag is a random string used an identification to track the temporary urls.
    The format is
    {tag1: {'create_time': t1, data},
    tag2:{'': t2, data},
    ...}.

    Instead of dict, the methods of the instance
     allow transfer data among modules. And it could manage the expiring.

    Well, I'm just unwilling to take time on learning flask Session, so
    I simply realize a class with same but less features."""
    def __init__(self):
        self.dict = dict()
        self.expire_time = st.EXPIRE_TIME

    def add(self, data):
        """Add the data, returns the tag identifying the data.
        TODO check the if tag repeats """
        tag = tools.random_string(st.TAG_LENGTH)
        info = {
            'create_time': int(time.time()),
            'data': data
        }
        self.dict[tag] = info

        return tag

    def check_expire(self, tag):
        """To check if this tag is expired"""
        try:
            create_time = self.dict[tag]['create_time']
        except KeyError:
            raise ExpireException

        if create_time + self.expire_time < time.time():
            self.dict.pop(tag)
            raise ExpireException

    def get_data(self, tag):
        """Return the data of this tag."""
        try:
            self.check_expire(tag)
            rslt = self.dict[tag]['data']
        except KeyError:
            raise ExpireException

        return rslt

    def update(self, tag, data):
        """Substitute the old data to the new one."""
        self.dict[tag]['data'] = data

        return


tags = Tags()


if __name__ == '__main__':
    t = tags.add('b')
    print(t, tags.get(t))
    time.sleep(1)
    print(t, tags.get(t))







